import theAxios from 'axios'
// 进度条
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from './token'
import store from '@/store'
// 封装uuid
import uuid from './uuid'

const axios = theAxios.create({
  baseURL: 'http://sph-h5-api.atguigu.cn',
  timeout: 5000
})

axios.interceptors.request.use(config => {
  // 进度条开始
  Nprogress.start()
  config.headers.userTempId = uuid()
  const token = getToken()
  if (token) {
    config.headers.token = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  // 进度条结束
  Nprogress.done()
  // token过期
  if (response.data.code === 208) {
    store.dispatch('user/_g_log_out', '登录过期,请重新登录')
    return new Promise(() => {
    })
  } else {
    return response.data
  }
}, error => {
  alert(error.message)
  return new Promise(() => {
  })
})

export default axios
